<template>
    <div id="stud">
      <!--1. 分页条件查询-->
      <el-form :inline="true" :model="studentSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名" size="medium"/>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址" size="medium"/>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级" size="medium">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="search" size="medium" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="addStudent" size="medium" icon="el-icon-plus">添加学生</el-button>
        </el-form-item>
      </el-form>
      <!--2. 分页数据的展示-->
      <el-table
        :data="students"
        stripe
        size="medium"
        style="width: 100%">
        <el-table-column
          label="学号"
          prop="sid"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="sname"
          align="center">
        </el-table-column>
        <el-table-column
          label="性别"
          prop="sex"
          align="center">
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="age"
          align="center">
        </el-table-column>
        <el-table-column
          label="住址"
          prop="addr"
          align="center">
        </el-table-column>
        <el-table-column
          label="所在班级"
          prop="cname"
          align="center">
        </el-table-column>

        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit"></el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)" icon="el-icon-delete"></el-button>
            </el-button-group>

          </template>
        </el-table-column>
      </el-table>
      <!--3. 编辑学生对话框-->
      <el-dialog :title="student.sid ? '修改学生' : '添加学生'" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        {{student}}
        <el-form :model="student"  :rules="rules" ref="ruleForm">
          <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
            <el-input v-model="student.sname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
            <el-radio v-model="student.sex" autocomplete="off" label="男">男</el-radio>
            <el-radio v-model="student.sex" autocomplete="off" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
            <el-input v-model.number="student.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
            <el-input v-model="student.addr" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
            <el-select v-model="student.cid" placeholder="请选择所在班级">
              <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
</template>

<script>
  import {findAll,search,save,delStud} from "@/api/students";
  import {findClasses} from "@/api/classes";

  export default {
    data() {
      const ageValidator=(rule,value,callback)=>{
        if(!value){
          callback(new Error('请输入学生年龄！'))
        }else if(!Number.isInteger(value)){
          callback(new Error("请输入一个整数！"))
        }else{
          callback()
        }
      }
      return {
        students: [],
        page:1,
        pageSize:3,
        total:100,
        studentSearch:{},
        classes:[],
        student:{},
        formLabelWidth:'100px',
        dialogFormVisible:false,
        // 表单验证
        rules:{
          sname:[
            {required:true,message:'必须输入学生姓名！',trigger:'blur'}
          ],
          sex:[
            {required: true,message:'必须选择学生性别！',trigger:'change'}
          ],
          age:[
            {validator: ageValidator,trigger:'blur'}
          ],
          addr:[
            {required:true,message:'必须输入学生住址！',trigger:'blur'}
          ],
          cid:[
            {required:true,message:'必须选择班级编号！',trigger:'change'}
          ]
        }
      }
    },
    created() {
      // this.findAllStudents()
      this.findClasses()
      this.search()
    },
    methods: {
      //1. 查询所有学生
      findAllStudents(){
        findAll().then((data)=>{
          if(data.code === 20000){
            this.students = data.students
          }
        })
      },
      //2. 查询所有班级
      findClasses(){
        findClasses().then((data)=>{
          console.log("data:",data)
          if(data.code === 20000){
            this.classes = data.data.classes
          }

        })
      },
      //3. 查询所有学生
      search(){
        search(this.page,this.pageSize,this.studentSearch).then(data=>{
         if(data.code === 20000){
           this.students = data.data.pr.rows
           this.total = data.data.pr.total
         }
        })
      },
      //4. 添加学生界面显示
      addStudent(){
        //4.1 清空学生对象
        this.student = {}
        //4.2 显示对话框
        this.dialogFormVisible = true
      },
      //5. 保存学生
      save(){
        //5.1 根据是否有sid的值决定请求是添加还是修改
        let url = '/student/add.do'
        if(this.student.sid){
          url = '/student/update.do'
        }
        //5.2 向后台发出请求
        let _this = this
         this.$refs['ruleForm'].validate(valid=>{
            if(valid){
              save(url,this.student).then((data)=>{
                if(data.code === 20000){
                  this.$message({
                    message: data.message,
                    type: 'success',
                    onClose(){
                      //1. 关闭对话框
                      _this.dialogFormVisible = false
                      _this.search()
                    }
                  });
                }
              })
            }
         })
      },
      //修改学生界面
      handleEdit(index, row) {
        console.log(index, row);
        //1. 将当前要修改的行数据赋值给学生对象
        this.student = row
        //2. 显示对话框
        this.dialogFormVisible = true
      },
      //删除学生
      handleDelete(index, row) {
        let _this = this
        this.$confirm(`你是真要要删除学生[${row.sname}]`, '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 向后台异步删除请求
          delStud(row.sid).then(data=>{
            if(data.code === 20000){
              this.$message({
                type: 'success',
                message: data.message,
                onClose(){
                  // 刷新页面
                  _this.search()
                }
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //页大小改变旱触发
      handleSizeChange(val) {
        this.pageSize = val
        this.search()
        console.log(`每页 ${val} 条`);
      },
      //当前页改变时触发
      handleCurrentChange(val) {
        this.page = val
        this.search()
        console.log(`当前页: ${val}`);
      }
    },

  }
</script>

<style scoped>
  #stud{
    margin: 20px;
  }
  .el-pagination{
    text-align: right;
    margin-top: 20px;
  }
</style>
